import {defineStore} from 'pinia'
import {deepClone, encryption} from "utils/util";
import {getMenu, getTopMenu, getUserInfo, loginByUsername, logout, updateCurrentUserInfo} from "@/api/user";
import useRouterStore from "@/stores/useRouterStore";

import useCommonStore from "@/stores/useCommonStore";
import {formatPath} from "@/router/avue-router";
import treeUtils from "utils/treeUtils";


const routerStore = () => {
    return useRouterStore();
}

const commonStore = () => {
    return useCommonStore()
}

const useUserStore = defineStore("userStore", {
        state: () => {
            return {
                token: null,
                permissionMap: {},
                menuId: {},
                menu: [],
                menuAll: [],
                userInfo: {},
                roles: [],
            }
        },
        getters: {
            userId: (state) => state.userInfo.id,
        },
        actions: {
            hasPermission(permission, defaultState = false) {
                if (permission === null || permission === undefined) {
                    return defaultState;
                }
                let btnPermissions = [];
                if (Array.isArray(permission)) {
                    btnPermissions = permission;
                } else if (typeof permission === 'string') {
                    permission += ""
                    btnPermissions = permission.split(",")
                }
                let permissions = btnPermissions.filter(e => e !== null && e !== undefined && e.length > 0)
                if (!permissions || permissions.length < 1) {
                    return defaultState;
                }
                let permissionMap = this.permissionMap;
                for (let i = 0; i < permissions.length; i++) {
                    let code = permissions[i]
                    if (!permissionMap[code]) {
                        return false;
                    }
                }
                return true;
            },
            login(userInfo) {
                const user = encryption({
                    data: userInfo,
                    type: 'Base64',
                    param: ['userName', 'password']
                });
                return new Promise((resolve) => {
                    loginByUsername(user.userName, user.password, userInfo.code, userInfo.redomStr).then(res => {
                        this.token = res.data.data;
                        routerStore().delAllTag();
                        commonStore().clearLockScreen()
                        resolve(res.data.data);
                    })
                })
            },   //根据手机号登录
            LoginByPhone(userInfo) {
                return new Promise((resolve) => {
                    loginByUsername(userInfo.phone, userInfo.code).then(res => {
                        this.token = res.data.data;
                        routerStore().delAllTag();
                        commonStore().clearLockScreen()
                        resolve();
                    })
                })
            },
            GetUserInfo() {
                return new Promise((resolve, reject) => {
                    getUserInfo().then((res) => {
                        const data = res.data.data;
                        this.userInfo = data.userInfo
                        this.roles = data.roles
                        let permissionMap = {};
                        for (let i = 0; i < data.permission.length; i++) {
                            permissionMap[data.permission[i]] = true
                        }
                        this.permissionMap = permissionMap
                        resolve(data);
                    }).catch(err => {
                        reject(err);
                    })
                })
            },
            updateUserInfo(data) {
                return new Promise((resolve, reject) => {
                    updateCurrentUserInfo(data).then((res) => {
                        let data = res.data.data
                        this.userInfo = data
                        resolve(data);
                    }).catch(err => {
                        reject(err);
                    })
                })
            },
            // 登出
            LogOut() {
                return new Promise((resolve, reject) => {
                    logout().then(() => {

                        this.menuAll = []
                        this.menu = []
                        this.roles = []
                        this.permissionMap = {}
                        this.token = null
                        // this.userInfo = {}
                        routerStore().delAllTag();
                        commonStore().clearLockScreen()
                        resolve()
                    }).catch(error => {
                        reject(error)
                    })
                })
            },
            //注销session
            FedLogOut() {
                return this.LogOut()
            },
            GetTopMenu() {
                return new Promise(resolve => {
                    getTopMenu().then((res) => {
                        const data = res.data.data || []
                        resolve(data)
                    })
                })
            },
            //获取系统菜单
            GetMenu(parentId) {
                return new Promise(resolve => {
                    getMenu(parentId).then((res) => {
                        let data = res.data.data || []
                        let menu = deepClone(data);
                        menu = treeUtils.listToTree(menu)
                        menu.forEach(ele => formatPath(ele, true));
                        this.menu = menu;
                        this.menuAll = menu;
                        resolve(menu)
                    })
                })
            },

        },
        persist: true,

    }
)
export default useUserStore
